package org.example.ruoxing_admin_springboot3.service.user;
import jakarta.annotation.Resource;
import org.example.ruoxing_admin_springboot3.dao.VerificationCodeDao;
import org.example.ruoxing_admin_springboot3.exceptionHandleUtils.ExceptionHandleUtils;
import org.example.ruoxing_admin_springboot3.httpResponseResult.ResponseResult;
import org.example.ruoxing_admin_springboot3.mapper.VerificationCodeMapper;
import org.example.ruoxing_admin_springboot3.utils.RandomCodeUtils;
import org.example.ruoxing_admin_springboot3.utils.TimestampUtil;
import org.example.ruoxing_admin_springboot3.utils.UUIDUtil;
import org.example.ruoxing_admin_springboot3.viewmodel.VerificationCodeVo;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * @description 用户验证码服务
 * @author 莫若省
 * @createTime 2024/5/9
*/
@Service
public class UserVerificationCodeService {
    @Resource
    VerificationCodeMapper verificationCodeMapper;
    /**
     * @description 创建验证码
     * @author 莫若省
     * @createTime 2024/5/9
    */
    public ResponseResult<Object> createVerificationCode() {
        try{
            //验证码过期时间1分钟
            long verificationCodeExpireTime = 60 * 1000;
            //当前的时间
            long currentTimeMillis = TimestampUtil.getCurrentMillisTimestamp();
            //生成验证码对象
            VerificationCodeVo verificationCodeVo = new VerificationCodeVo();
            verificationCodeVo.setVerificationCode(RandomCodeUtils.createRandomCode(4));
            verificationCodeVo.setVerificationCodeId(UUIDUtil.generateUpperCaseUUID());
            verificationCodeVo.setCreateTime(currentTimeMillis);
            //取出目前库内的全部验证码
            List<VerificationCodeDao> verificationCodeDaoList = verificationCodeMapper.selectVerificationCodeAll();
            for (VerificationCodeDao verificationCodeDao : verificationCodeDaoList) {
                //当前时间减去验证码创建时间小于验证码过期时间，则证明该验证码已经过期，则删除该验证码
                if (currentTimeMillis - verificationCodeDao.getCreateTime()  < verificationCodeExpireTime) {
                    verificationCodeMapper.deleteVerificationCodeById(verificationCodeDao.getVerificationCodeId());
                }
            }
            //生成验证码Dao对象
            VerificationCodeDao verificationCodeDao = new VerificationCodeDao();
            verificationCodeDao.setVerificationCodeId(verificationCodeVo.getVerificationCodeId());
            verificationCodeDao.setCreateTime(verificationCodeVo.getCreateTime());
            //新验证码对象入库
            int insertCount =  verificationCodeMapper.insertVerificationCode(verificationCodeDao);
            if (insertCount > 0) {
                return ResponseResult.SUCCESS(verificationCodeVo);
            }else {
                return ResponseResult.WARN("生成验证码失败!");
            }

        }catch (Exception e){
            System.out.println(e.getMessage());
            ExceptionHandleUtils.reportException(e, "生成验证码失败!");
            return ResponseResult.ERROR();
        }
    }
}
